// 统一的注册所有的全局组件
import XtxSkeleton from '@/components/skeleton/index.vue'
import Xtxcarousel from './carousel/index.vue'
import XtxMore from './more/index.vue'
import { App } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'
import XtxBread from './bread/index.vue'
import BreadItem from './bread/item.vue'
import XtxCity from './city/index.vue'
export default {
  install(app: App) {
    app.component(XtxSkeleton.name,XtxSkeleton)
    app.component('Xtxcarousel',Xtxcarousel),
    app.component('XtxMore',XtxMore)
    app.component('XtxBread',XtxBread)
    app.component('BreadItem',BreadItem)
    app.component('XtxCity',XtxCity)
    
    // 注册全局指令
    app.directive('lazy', {
      // Vue2: 当绑定的元素插入到 DOM 中时执行, inserted
      // inserted(el, binding) {}
      // Vue3: 改为了 mounted
      mounted(el, binding) {
        // el: 当前指令绑定的 DOM 元素
        // console.log(el, binding)
        // 逻辑: 当 el 进入可视区后, 给它设置 src 属性
  const {stop}= useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 停止监听
            stop()
            el.src = binding.value
          }
        })
        // 如果图片加载失败,给个默认图片
        el.onerror = function () {
          el.src =  defaultImg
        }
      },
    })
  }
}